# pythonProject5/api/v1/records.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Union
from datetime import datetime, timedelta
from sqlalchemy import func
import os
import logging
# 正确导入模型
from models.db import TranslationRecord, ASRRecord  # 假设你的记录模型在这里
from models.db import User  # 用户模型来自 models.user

# 导入 Pydantic 模型
from schemas.auth import UserOut
from schemas.record import ASRRecordCreate, TranslationRecordCreate

# 导入依赖
from db.session import get_db_session as get_db  # 与 auth.py 保持一致
from core.security import get_current_user

# Pydantic 基类
from pydantic import BaseModel

logger = logging.getLogger(__name__)

# =======================
# 请求模型定义
# =======================
class BatchDeleteRequest(BaseModel):
    record_ids: List[int]

router = APIRouter(prefix="/records", tags=["Records"])

# =======================
# 响应模型定义
# =======================

class ASRRecordResponse(BaseModel):
    record_type: str = "asr"
    id: int
    filename: str
    text: str
    language: str
    duration_seconds: float
    file_size: int
    audio_path: str = None
    created_at: datetime

    class Config:
        from_attributes = True


class TranslationRecordResponse(BaseModel):
    record_type: str = "translation"
    id: int
    source_text: str
    target_text: str
    source_language: str  # 修改为与数据库模型匹配
    target_language: str  # 修改为与数据库模型匹配
    duration_seconds: float  # 修改为与数据库模型匹配
    audio_path: str = None
    created_at: datetime

    class Config:
        from_attributes = True


# 联合响应类型
RecordResponse = Union[ASRRecordResponse, TranslationRecordResponse]


# =======================
# 接口 1: 获取用户所有记录
# =======================
@router.get("/", response_model=List[RecordResponse])
def get_user_records(
    days: int = 7,
    limit: int = 50,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取当前用户的 ASR 和翻译记录，合并返回。
    """
    user_id = current_user.id
    start_date = datetime.utcnow() - timedelta(days=days)

    # 查询 ASR 记录
    asr_records = db.query(ASRRecord).filter(
        ASRRecord.user_id == user_id,
        ASRRecord.created_at >= start_date
    ).order_by(ASRRecord.created_at.desc()).limit(limit).all()

    # 查询翻译记录
    translation_records = db.query(TranslationRecord).filter(
        TranslationRecord.user_id == user_id,
        TranslationRecord.created_at >= start_date
    ).order_by(TranslationRecord.created_at.desc()).limit(limit).all()

    # 合并记录
    all_records = []

    for record in asr_records:
        all_records.append(ASRRecordResponse.model_validate(record))

    for record in translation_records:
        all_records.append(TranslationRecordResponse.model_validate(record))

    # 按时间倒序排序
    all_records.sort(key=lambda x: x.created_at, reverse=True)

    return all_records[:limit]


# =======================
# 接口 2: 用户统计
# =======================
@router.get("/stats")
def get_user_stats(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取用户使用统计
    """
    user_id = current_user.id

    total_asr = db.query(ASRRecord).filter(ASRRecord.user_id == user_id).count()
    total_translation = db.query(TranslationRecord).filter(TranslationRecord.user_id == user_id).count()
    total = total_asr + total_translation

    last_week = datetime.utcnow() - timedelta(days=7)
    weekly_asr = db.query(ASRRecord).filter(
        ASRRecord.user_id == user_id,
        ASRRecord.created_at >= last_week
    ).count()
    weekly_translation = db.query(TranslationRecord).filter(
        TranslationRecord.user_id == user_id,
        TranslationRecord.created_at >= last_week
    ).count()
    weekly = weekly_asr + weekly_translation

    # 获取最后一次活动时间
    last_activity = db.query(
        func.max(ASRRecord.created_at)
    ).filter(ASRRecord.user_id == user_id).scalar()

    last_translation = db.query(
        func.max(TranslationRecord.created_at)
    ).filter(TranslationRecord.user_id == user_id).scalar()

    latest_activity = max(
        filter(None, [last_activity, last_translation]),
        default=None
    )

    return {
        "total_records": total,
        "total_asr": total_asr,
        "total_translation": total_translation,
        "last_7_days": weekly,
        "last_7_days_asr": weekly_asr,
        "last_7_days_translation": weekly_translation,
        "last_activity": latest_activity.isoformat() if latest_activity else None
    }

# =======================
# 接口 3: 创建 ASR 记录
# =======================
@router.post("/asr", response_model=ASRRecordResponse)
def create_asr_record(
    record: ASRRecordCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    创建新的语音识别记录
    """
    try:
        new_record = ASRRecord(
            user_id=current_user.id,
            filename=record.filename,
            text=record.text,
            language=record.language,
            duration_seconds=record.duration_seconds,
            file_size=record.file_size,
            audio_path=record.audio_path,
            model_used=record.model_used
        )
        
        db.add(new_record)
        db.commit()
        db.refresh(new_record)
        
        return ASRRecordResponse.model_validate(new_record)
    except Exception as e:
        db.rollback()
        logger.error(f"创建ASR记录失败: {e}")
        raise HTTPException(status_code=500, detail=f"创建ASR记录失败: {str(e)}")


# =======================
# 接口 4: 创建翻译记录
# =======================
@router.post("/translation", response_model=TranslationRecordResponse)
def create_translation_record(
    record: TranslationRecordCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    创建新的翻译记录
    """
    try:
        new_record = TranslationRecord(
            user_id=current_user.id,
            source_text=record.source_text,
            target_text=record.target_text,
            source_language=record.source_language,
            target_language=record.target_language,
            duration_seconds=record.duration_seconds,
            source_audio_path=record.source_audio_path,
            model_used=record.model_used,
            translation_engine=record.translation_engine
        )
        
        db.add(new_record)
        db.commit()
        db.refresh(new_record)
        
        return TranslationRecordResponse.model_validate(new_record)
    except Exception as e:
        db.rollback()
        logger.error(f"创建翻译记录失败: {e}")
        raise HTTPException(status_code=500, detail=f"创建翻译记录失败: {str(e)}")


# =======================
# 接口 5: 批量删除记录
# =======================
@router.delete("/batch")
def delete_records_batch(
    request: BatchDeleteRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    批量删除指定的历史记录
    请求体: {"record_ids": [1, 2, 3, 4]}
    """
    try:
        record_ids = request.record_ids
        if not record_ids:
            raise HTTPException(status_code=400, detail="record_ids 不能为空")
        
        deleted_asr = 0
        deleted_translation = 0
        not_found_ids = []
        
        for record_id in record_ids:
            # 查找ASR记录
            asr_record = db.query(ASRRecord).filter(
                ASRRecord.id == record_id,
                ASRRecord.user_id == current_user.id
            ).first()
            
            if asr_record:
                # 删除关联的音频文件
                if asr_record.audio_path and os.path.exists(asr_record.audio_path):
                    try:
                        os.remove(asr_record.audio_path)
                    except Exception as e:
                        logger.warning(f"删除音频文件失败: {e}")
                
                db.delete(asr_record)
                deleted_asr += 1
                continue
            
            # 查找翻译记录
            translation_record = db.query(TranslationRecord).filter(
                TranslationRecord.id == record_id,
                TranslationRecord.user_id == current_user.id
            ).first()
            
            if translation_record:
                # 删除关联的音频文件
                if translation_record.source_audio_path and os.path.exists(translation_record.source_audio_path):
                    try:
                        os.remove(translation_record.source_audio_path)
                    except Exception as e:
                        logger.warning(f"删除音频文件失败: {e}")
                
                db.delete(translation_record)
                deleted_translation += 1
            else:
                not_found_ids.append(record_id)
        
        db.commit()
        
        return {
            "message": "批量删除完成",
            "deleted_asr": deleted_asr,
            "deleted_translation": deleted_translation,
            "total_deleted": deleted_asr + deleted_translation,
            "not_found_ids": not_found_ids
        }
        
    except HTTPException:
        # 重新抛出HTTP异常
        raise
    except Exception as e:
        db.rollback()
        logger.error(f"批量删除记录失败: {e}")
        raise HTTPException(status_code=500, detail=f"批量删除记录失败: {str(e)}")


# =======================
# 接口 6: 删除单条记录
# =======================
@router.delete("/{record_id}")
def delete_record(
    record_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    删除指定的历史记录（ASR或翻译记录）
    """
    try:
        # 先查找ASR记录
        asr_record = db.query(ASRRecord).filter(
            ASRRecord.id == record_id,
            ASRRecord.user_id == current_user.id
        ).first()
        
        if asr_record:
            # 删除关联的音频文件（如果存在）
            if asr_record.audio_path and os.path.exists(asr_record.audio_path):
                try:
                    os.remove(asr_record.audio_path)
                except Exception as e:
                    logger.warning(f"删除音频文件失败: {e}")
            
            db.delete(asr_record)
            db.commit()
            return {"message": f"ASR记录 {record_id} 已删除", "record_type": "asr"}
        
        # 如果不是ASR记录，查找翻译记录
        translation_record = db.query(TranslationRecord).filter(
            TranslationRecord.id == record_id,
            TranslationRecord.user_id == current_user.id
        ).first()
        
        if translation_record:
            # 删除关联的音频文件（如果存在）
            if translation_record.source_audio_path and os.path.exists(translation_record.source_audio_path):
                try:
                    os.remove(translation_record.source_audio_path)
                except Exception as e:
                    logger.warning(f"删除音频文件失败: {e}")
            
            db.delete(translation_record)
            db.commit()
            return {"message": f"翻译记录 {record_id} 已删除", "record_type": "translation"}
        
        # 记录不存在
        raise HTTPException(status_code=404, detail="记录不存在或无权限删除")
        
    except HTTPException:
        # 重新抛出HTTP异常
        raise
    except Exception as e:
        db.rollback()
        logger.error(f"删除记录失败: {e}")
        raise HTTPException(status_code=500, detail=f"删除记录失败: {str(e)}")


# =======================
# 接口 7: 清空所有历史记录
# =======================
@router.delete("/clear/all")
def clear_all_records(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    清空当前用户的所有历史记录
    """
    try:
        # 获取用户的所有记录以便删除音频文件
        asr_records = db.query(ASRRecord).filter(ASRRecord.user_id == current_user.id).all()
        translation_records = db.query(TranslationRecord).filter(TranslationRecord.user_id == current_user.id).all()
        
        # 删除ASR记录的音频文件
        for record in asr_records:
            if record.audio_path and os.path.exists(record.audio_path):
                try:
                    os.remove(record.audio_path)
                except Exception as e:
                    logger.warning(f"删除音频文件失败: {e}")
        
        # 删除翻译记录的音频文件
        for record in translation_records:
            if record.source_audio_path and os.path.exists(record.source_audio_path):
                try:
                    os.remove(record.source_audio_path)
                except Exception as e:
                    logger.warning(f"删除音频文件失败: {e}")
        
        # 删除数据库记录
        asr_count = db.query(ASRRecord).filter(ASRRecord.user_id == current_user.id).count()
        translation_count = db.query(TranslationRecord).filter(TranslationRecord.user_id == current_user.id).count()
        
        db.query(ASRRecord).filter(ASRRecord.user_id == current_user.id).delete()
        db.query(TranslationRecord).filter(TranslationRecord.user_id == current_user.id).delete()
        db.commit()
        
        return {
            "message": "所有历史记录已清空",
            "deleted_asr": asr_count,
            "deleted_translation": translation_count,
            "total_deleted": asr_count + translation_count
        }
        
    except Exception as e:
        db.rollback()
        logger.error(f"清空所有记录失败: {e}")
        raise HTTPException(status_code=500, detail=f"清空所有记录失败: {str(e)}")